package com.wedimob.slideshare.source;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.wedimob.slideshare.KeyWordType;
import com.wedimob.slideshare.SearchCriteria;
import com.wedimob.slideshare.SortBy;

public class SlideShareStrategy implements SourceStrategy {

    public final static String URL_BASE = "http://fr.slideshare.net";
    public final static String SEARCH_PATTERN = URL_BASE + "/search";
    public final static String USER_PAGE_PATTERN = URL_BASE + "/{username}";
    public final static String USER_DOC_PAGE_PATTERN = URL_BASE + "/{username}/slideshelf";
    private final static double NB_ITEM_PER_PAGE = 12.0;

    @Override
    public String getUrlBase() {
        return URL_BASE;
    }

    @Override
    public List<URL> generateUrl(SearchCriteria criteria) {
        try {
            List<URL> result = new ArrayList<URL>();
            int nbPages = Source.getNbPages(criteria.getLimit(), NB_ITEM_PER_PAGE);
            int begin = (int) Math.floor(criteria.getBegin() / NB_ITEM_PER_PAGE);
            for (int i = begin; i < begin + nbPages; i++) {
                result.add(new URL(URL_BASE + "/search/"
                        + convert(criteria.getKeyWordType()) + "?lang=%2A%2A&page=" + (i + 1) + "&q="
                        + criteria.getKeyword().replaceAll(" ", "+")
                        + "&searchfrom=header&sort=" + convert(criteria.getSortBy())));
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String convert(SortBy sortBy) {
        switch (sortBy) {
        case RELEVANCE:
            return "relevance";
        case LAST_PUBLICATION:
            return "tout dernier";
        case POPULARITY:
            return "vues";
        }
        return null;
    }

    private String convert(KeyWordType keyWordType) {
        switch (keyWordType) {
        case CONTENT:
            return "slideshow";
        case USER:
            return "user";
        }
        return null;
    }
}
